package com.canyou.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.canyou.api.BaseApiController;
import com.canyou.api.ResponseBO;
import com.canyou.constants.MsgConstants;
import com.canyou.system.entity.perm.PermissionTreeVO;
import com.canyou.system.entity.role.RoleDTO;
import com.canyou.system.entity.role.RoleMenuDTO;
import com.canyou.system.model.Role;
import com.canyou.system.service.RoleMenuService;
import com.canyou.system.service.RoleService;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

import static com.canyou.api.ResponseBO.*;

/**
 * 角色管理控制器
 *
 * @author canyou
 * @since 2019-05-14
 */
@Api(tags = "角色管理")
@ApiSort(1002)
@RestController
@RequestMapping("/role")
@Validated
public class RoleController extends BaseApiController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @ApiOperation(value = "获取角色分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNumber", paramType = "query", value = "当前第几页", dataType = "int", example = PAGE_INDEX),
            @ApiImplicitParam(name = "pageSize", paramType = "query", value = "每页记录数", dataType = "int", example = PAGE_SIZE),
            @ApiImplicitParam(name = "roleName", paramType = "query", value = "角色名称", dataType = "string", example = "管理员")
    })
    @PreAuthorize("hasPerm('role')")
    @GetMapping("/get_page")
    public ResponseBO<IPage<Role>> getPageList(@RequestParam(defaultValue = PAGE_INDEX, required = false) int pageNumber,
                                               @RequestParam(defaultValue = PAGE_SIZE, required = false) int pageSize,
                                               @RequestParam(required = false) String roleName) {
        IPage<Role> page = new Page<>(pageNumber, pageSize);
        IPage<Role> pageList = roleService.getPageList(page, roleName);
        return ok(pageList);
    }

    @ApiOperation(value = "获取角色详情")
    @ApiImplicitParam(name = "id", paramType = "query", value = "角色id", dataType = "int", required = true, example = "1")
    @PreAuthorize("hasPerm('role')")
    @GetMapping("/get_info")
    public ResponseBO<Role> getRoleInfo(@NotNull(message = "角色id不能为空")
                                        @RequestParam(required = false) Long id) {
        return ok(roleService.getById(id));
    }

    @ApiOperation(value = "获取角色权限")
    @ApiImplicitParam(name = "roleId", paramType = "query", value = "角色id", dataType = "Long", example = "1")
    @PreAuthorize("hasPerm('role')")
    @GetMapping("/get_menus_by_role_id")
    public ResponseBO<List<PermissionTreeVO>> getRoleMenuByRoleId(@NotNull(message = "角色id不能为空")
                                                                  @RequestParam Long roleId) {
        List<PermissionTreeVO> roleMenuTree = roleMenuService.getRoleMenuByRoleId(roleId);
        return ok(roleMenuTree);
    }

    @ApiOperation(value = "新增编辑角色")
    @PreAuthorize("hasPerm('role:add','role:edit')")
    @PostMapping("/save")
    public ResponseBO saveRole(@ApiParam(name = "roleDTO", type = "RoleDTO", value = "角色新增编辑数据", required = true)
                               @Valid
                               @NotNull(message = "角色信息不能为空")
                               @RequestBody RoleDTO roleDTO) {
        Long roleId = roleDTO.getId();
        if (roleService.existRole(roleDTO.getRoleName(), roleId)) {
            return illegal("角色名已存在");
        }
        Role role = new Role();
        if (roleId != null) {
            role = roleService.getById(roleId);
            if (role == null) {
                return illegal("roleId: " + roleId + "对应的角色不存在");
            }
        }
        BeanUtils.copyProperties(roleDTO, role);
        boolean res = roleService.saveOrUpdate(role);
        return result(res, roleId);
    }

    @ApiOperation(value = "保存角色权限")
    @PreAuthorize("hasPerm('role:permission')")
    @PostMapping("/save_role_menu")
    public ResponseBO saveRoleMenu(@ApiParam(name = "roleMenuDTO", type = "RoleMenuDTO", value = "角色权限新增编辑数据", required = true)
                                   @Valid
                                   @NotNull(message = "角色权限信息不能为空")
                                   @RequestBody RoleMenuDTO roleMenuDTO) {
        if (!roleService.saveRoleMenu(roleMenuDTO)) {
            return illegal("保存角色菜单权限失败");
        } else {
            return ok("保存角色菜单权限成功");
        }
    }

    @ApiOperation(value = "删除角色")
    @PreAuthorize("hasPerm('role:del')")
    @PostMapping("/remove")
    public ResponseBO removeRole(@ApiParam(name = "id", type = "Long", value = "角色id", required = true, example = "1")
                                 @Valid
                                 @NotNull(message = "角色id不能为空")
                                 @RequestBody Long id) {
        if (roleService.existRoleUser(id)) {
            return illegal("角色已分配用户, 不能删除");
        }
        return ok(roleService.removeRoleById(id), MsgConstants.DEL_SUCCESS);
    }

}
